/*
 * @Author: xinyang3
 * @Date: 2021-09-03 09:49
 * @Descripttion: fetch 封装
 * @LastEditors: xinyang3
 * @LastEditTime: 2021-11-16 14:43
 */
import $qs from 'qs';

const url_prefiex = `/bgmg`;
const request = {};

function isArray(array) {
  const toString = Object.prototype.toString;
  const isarray =
    Array.isArray ||
    function (arg) {
      return toString.call(arg) === '[object Array]';
    };
  return isarray(array);
}

function getfetch() {
  const fetch = window.fetch || self.fetch || undefined;

  if (!fetch) {
    return console.warn('browser fetch api is not supported.');
  }
  return fetch;
}
const fetchs = getfetch();

const option = {
  cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
  // credentials: "same-origin", // include, same-origin, *omit
  headers: {
    // "user-agent": "Mozilla/4.0 MDN Example",
    'Content-Type': 'application/json',
  },
  method: 'get', // *GET, POST, PUT, DELETE, etc.
  mode: 'cors', // no-cors, cors, *same-origin
  redirect: 'follow', // manual, *follow, error
  referrer: 'no-referrer', // *client, no-referrer
};

/**
 * @description: get request
 * @param {*} url
 * @param {*} params
 * @return {*}
 */
request.get = async function (url, params = {}) {
  const options = Object.assign({}, option, {
    // body: JSON.stringify(params)
  });
  url = url_prefiex + url + '?' + $qs.stringify(params);
  const response = await fetchs(url, options);
  const data = await response.json();
  return data;
};
/**
 * @description: post
 * @param {*} url
 * @param {*} data
 * @return {*}
 */
request.post = function (url, data = {}) {
  const options = Object.assign({}, option, {
    method: 'post',
    body: JSON.stringify(data),
  });
  url = url_prefiex + url;
  return fetchs(url, options).then((response) => {
    return response.json();
  });
};

request.postForm = function (url, data = {}) {
  const formdata = new FormData();
  Object.keys(data).forEach((key) => {
    if (isArray(data[key])) {
      data[key].forEach((item, index) => {
        formdata.append(key + '[' + index + ']', item);
      });
    } else {
      formdata.append(key, data[key]);
    }
  });

  const options = Object.assign({}, option, {
    headers: {
      // 'Content-Type': 'multipart/form-data;charset=utf-8;'
    },
    method: 'post',
    body: formdata,
  });
  url = url_prefiex + url;
  return fetchs(url, options).then((response) => {
    return response.json();
  });
};
/**
 * @description:delete one
 * @param {*} data
 * @return {*}
 */
request.deleteOne = function (url, params) {
  const options = Object.assign({}, option, {
    method: 'delete',
  });
  url = url_prefiex + url + '?' + $qs.stringify(params);
  return fetchs(url, options).then((response) => {
    return response.json();
  });
};

export default request;
